Integrating React with other JavaScript libraries
The biggest difference between React and JavaScript is the way they interact with the DOM. React has no idea of any changes made to the DOM outside of its scope. If jQuery or another library manipulates the same DOM nodes, React won’t be able to recover from the unknown DOM changes and conflicts between internal representation and actual DOM.
How to integrate jQuery
Just like a regular application, you need to install jQuery first.
Open the command prompt and cd (change directory) to your project folder where the package.json file exists. Now write down the following command to install jQuery using npm.
>npm install jquery –save
How to import jQuery
After you have jQuery up and running at your local computer, import $ from jQuery into your React file.
The import statements will look something like the following:
import React from 'react' import ReactDOM from 'react-dom' import { findDOMNode } from 'react-dom' import $ from 'jquery'
Convert jQuery code to React
The following jQuery code could be rewritten in React.
jQuery
$('#container').html('<button id="btn">Hello World</button>'); $('#btn').click(function() { console.log("hello world"); });
React
function Button(props) { return <button onClick = { props.onClick } > Say Hello < /button>; } function SayHello() { function handleClick() { console.log("hello world"); } return <Button onClick = { handleClick } />; } ReactDOM.render( < SayHello / > , document.getElementById('container'));
How to approach the jQuery integration
To embed jQuery in React, you need componentDidMount()
lifecycle method of the React component as a wrapper.
class App extends React.Component { componentDidMount() { // Jquery code goes here $(...)... } // ... }
To prevent React from manipulating the DOM element after mounting, you should return an empty <div/>
without any props or children from the render()
function. The React won’t modify an empty element, leaving the jQuery alone to manage the DOM.
render() { return <div ref = { e1 => this.e1 = e1 } />; }
If jQuery attaches an event listener to the DOM, it is important to detach it using the componentWillUnmount.
Example
Let’s create a simple Accordion in React.
We are going to create two React component – App and Accordion.
The React component App will have the necessary JSX to create the structure of the Accordion.
Whereas the other component Accordion will be responsible to execute the jQuery code.
The HTML of accordion
<div class="accor"> <div class="head">Quote 1</div> <div class="body"> <p>Any fool can write code that a computer can understand. Good programmers write code that humans can understand. </p> </div> </div>
The JSX equivalent of the above code will be:
class App extends React.Component { render() { return ( <div className = "accor-container" > <Accordion > <div className = "accor" > <div className = "head" > Quote 1 </div> <div className = "body" > <p> Any fool can write code that a computer can understand.Good programmers write code that humans can understand. < /p> </div> </div> <div className = "accor" > <div className = "head" > Quote 2 </div> <div className = "body" > <p > Give a man a program, frustrate him for a day.Teach a man to program, frustrate him for a lifetime. </p> </div></div> </Accordion> </div> ); } }
Another component is rather complicated and contains the jQuery code.
The function handleClick()
is responsible for the Accordion toggle effect.
handleClick() { const acc = this._acc.children; for (let i = 0; i < acc.length; i++) { let a = acc[i]; a.onclick = () => a.classList.toggle("active"); } }
The const variable acc
will refer to the DOM element of the accordion and on click, the jQuery toggle()
effect is initiated.
Next, we will implement the componentDidMount()
lifecycle method of the React to integrate jQuery in the React app.
componentDidMount() { this.handleClick(); }
The code of the Accordion component will be:
class Accordion extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } componentDidMount() { this.handleClick(); } handleClick() { const acc = this.acc.children; for (let i = 0; i < acc.length; i++) { let a = acc[i]; a.onclick = () => a.classList.toggle("active"); } } render() { return ( <div ref = { a => this.acc = a } onClick = { this.handleClick } > { this.props.children } </div> ) } }
React doesn’t assign any special meaning to this.acc = a
. It only works because we have assigned a reference in the render()
method. This is enough to get the Accordion component to render. This will associate the jQuery onClick event on the <div>
managed by jQuery.
Style.css
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,900); * { font-family: "Roboto"; box-sizing: border-box; } h1 { margin: 0px; padding: 10px; color: #333; font-size: 26px; background: #ddd; border-bottom: 1px solid #ccc; } .accor-container { width: 400px; margin: 10px auto 30px auto; text-align: left; } .accor { margin: 10px; border: 1px solid #ddd; transition: 0.4s; } .accor .head { background: #eee; padding: 10px 20px; cursor: pointer; } .accor .body { background: #fafafa; padding: 0 20px; max-height: 0; overflow: hidden; transition: 200ms ease-in-out; font-size: 90%; color: grey; } .accor.active>.body { padding: 10px 20px; max-height: 600px; }
To import style.css in the index.js, use the following.
import style from './style.css'
After you have done with the component part, render the App component.
ReactDOM.render(<App />, document.getElementById('root'));
This may seem a little overwhelming to you. Well, integrating JavaScript libraries is an advanced topic and needs a comprehensive understanding of ES6 and React.
Get yourself familiar with the whole code and then try the code yourself. In case, you feel stuck, please feel free to leave your question in the comments section below.
React Forms Handling << | Tutorial Home | >> React and PHP |
Comments